<template>
  <div class="geography-update-container">
    <el-form label-position="left" inline class="demo-table-expand">
      <el-form-item label="贴图">
        <ossUpload :imageUrl="detailData.src ? domain + detailData.src : ''" dirname="Adventure" :imgName="randomName"
          @upload-img="handler"></ossUpload>
      </el-form-item>
      <el-form-item label="名称">
        <el-input v-model="detailData.name" placeholder="请输入内容"></el-input>
      </el-form-item>
      <el-form-item prop="tag" label="标签">
        <el-select v-model="detailData.tag" multiple placeholder="请选择">
          <el-option v-for="item in options" :key="item._id" :label="item.name" :value="item._id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="生成地">
        <CompositionItem :selectedArr.sync="detailData.origin" :showNum="false" :module="['geographys']" />
      </el-form-item>

      <mavon-editor v-model="detailData.content" @save="update" @imgAdd="imgUpload" class="editor-sty"
        :boxShadow="false" ref="md"></mavon-editor>
    </el-form>
  </div>
</template>

<script>
  import OSS from "ali-oss";
  import ossUpload from "@/components/ossUpload.vue";
  import md5 from "md5-js";
  import CompositionItem from "@/components/CompositionItem.vue";

  export default {
    name: "GeographyAddorUpdate",
    data() {
      return {
        options: [],
        detailData: {
          src: "",
          version: this.$store.state.version,
          tag: [],
          origin: [],
          content: ""
        },
        loading: true,
        remoteOptions: []
      };
    },
    components: {
      ossUpload,
      CompositionItem
    },
    created() {
      let id = this.$route.query.id;
      if (id) {
        this.getDetailData(id);
      }
      this.getTag();
    },
    computed: {
      randomName() {
        let time = new Date();
        return md5(time);
      }
    },
    watch: {},
    methods: {
      async getTag() {
        let res = await this.$store.dispatch("getTags", {
          kind: "geographys"
        });
        this.options = res;
      },
      handler(src) {
        this.detailData.src = src;
      },
      /**
       * 获取详情
       * @param id
       */
      getDetailData(id) {
        this.axios
          .get("/geography/single", {
            params: {
              id
            }
          })
          .then(res => {
            let temp = this.showDataTransform(res.data, [
              { needNum: true, key: "origin" }
            ]);
            this.detailData = temp;
          });
      },
      changeOrigin() {
        return this.remoteOptions.filter(val => {
          return this.origin.some(value => {
            return value === val.name;
          });
        });
      },
      /**
       * 修改
       */
      async update() {
        let requestUrl =
          this.$route.query.type === "edit"
            ? "/geography/update"
            : "/geography/add";
        let [_origin] = this.transformSumbitData([
          {
            list: this.detailData.origin,
            needNum: true
          }
        ]);
        let res = await this.axios.post(requestUrl, {
          version: this.$store.state.version,
          ...this.detailData,
          origin: _origin
        });
        if (!res.data.code) {
          this.$message.success("添加成功");
        }
      },
      imgUpload(filename, $file) {
        // oss配置
        const client = new OSS({
          endpoint: "oss-cn-beijing.aliyuncs.com",
          accessKeyId: "LTAI4FgrsFXo8ij335BxeRbp",
          accessKeySecret: "oG0PWkV0qOeDoJQfwEHOqIvTp16S0x",
          bucket: "stavebox"
        });
        // 图片路径拼接，dirName其实就是定义存在oss的哪个虚拟文件夹下的
        let time = new Date();
        let hash = md5(time);
        let imgType = $file.type.split("/")[1];
        let hashName = "Adventure/" + hash + "." + imgType;
        // 将文件流上传至oss
        client
          .put(hashName, $file)
          .then(res => {
            let imgUrl = "http://img.fireleaves.cn/" + res.name;
            this.$refs.md.$img2Url(filename, imgUrl);
          })
          .catch(err => {
            console.log(err);
          });
      }
    }
  };
</script>

<style lang="scss">
  .geography-update-container {
    .demo-table-expand {
      font-size: 0;
    }

    .demo-table-expand label {
      width: 90px;
      color: #99a9bf;
    }

    .demo-table-expand .el-form-item {
      margin-right: 0;
      margin-bottom: 16px;
      width: 50%;
    }

    .el-input__inner {
      width: 221px;
    }

    .composition-sty .el-input__inner {
      width: 160px;
    }

    .editor-sty {
      z-index: 1;
      height: 80vh;
    }

    .oss-upload-container {
      .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;

        img {
          width: 220px;
        }
      }

      .avatar-uploader .el-upload:hover {
        border-color: #409eff;
      }

      .avatar-uploader-icon {
        font-size: 36px;
        color: #8c939d;
        width: 220px;
        height: 110px;
        line-height: 110px;
        text-align: center;
      }

      .avatar {
        width: 560px;
        height: auto;
        display: block;
      }
    }
  }
</style>

<style lang="scss" scoped>
  .geography-update-container {
    padding: 16px;
  }
</style>